#include "ParticuleSystem.h"
#include "ParticleComponent.h"
#include "PhysicComponents.h"
#include "PositionComponent.h"

ParticuleSystem::ParticuleSystem()
{

}
void ParticuleSystem::update(float dt)
{
	std::vector<int> toDelete;

	for(std::set<int>::iterator itr = mpt_entitiesID.begin(); itr != mpt_entitiesID.end();)
	{
		if(entityManager->hasEntity((*itr)))
		{
			ParticleComponentPtr particle = entityManager->getEntity(*itr)->getAs<ParticleComponent>();
			particle->time -= dt;

			if(!particle->physic)
			{
				PositionComponentPtr position = entityManager->getEntity(*itr)->getAs<PositionComponent>();
				position->m_position += dt * particle->speed * particle->direction;
			}
			else
			{
				JumpingComponentPtr phys = entityManager->getEntity(*itr)->getAs<JumpingComponent>();
				
				phys->jumpState += phys->jumpLength*dt;
				if(phys->jumpState>1)
					phys->jumpState = 1;

				if(phys->collide)
				{
					if(phys->normalCollision.x != 0 && phys->normalCollision.y == 0)
						particle->horizontalOrientation *= -1;
					if(phys->normalCollision.y != 0)
					{
						if(phys->normalCollision.y < 0) 
						{
							phys->jumpState = -phys->jumpState/2;

							if(phys->jumpState > -0.25)
							{
								particle->stop = true;
							}
						}
					}
				}
				
				if(!particle->stop)
				{
					particle->direction.x *= particle->horizontalOrientation;
					particle->direction.y = phys->jumpSpeed*phys->jumpState;

					sf::Vector2f result(particle->direction);
					result.x *= phys->speed;
					phys->moveDirection = result;
				}

				
			}
			if(particle->time < 0)
				toDelete.push_back(*itr);
			itr++;
		}
		else
		{
#ifdef DEFINE_MODE
			std::string str = "BUG PARTICULE : ";
			str += boost::lexical_cast<std::string>(*itr);
			BPL::Logger::log(str.c_str());
#endif
			itr = mpt_entitiesID.erase(itr);
		}
	}

	for(std::vector<int>::iterator toKill = toDelete.begin(); toKill != toDelete.end(); toKill++)
	{
		entityManager->killEntity(*toKill);
	}
}